import android.os.Handler
import android.os.Looper
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.retrofit.FastMultiUrl
import com.aries.library.fast.retrofit.FastObserver
import com.aries.library.fast.util.FastStackUtil
import com.dcjt.firehotcarpad.entity.CarCurrentDetailEntity
import com.dcjt.firehotcarpad.retrofit1.repository.ApiRepository1
import com.google.gson.Gson
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit


/**
 * Created by cj on 2021/2/22.
 * Email:codesexy@163.com
 * Function:
 * desc:为整个应用提供车辆状态服务
 */
class CarStatePool private constructor(
    private val mDispatchEngine: ExecutorService = Executors.newSingleThreadExecutor(),
    private val mHandler: Handler = Handler(Looper.getMainLooper())
) {

    /**
     * 当前车辆信息
     */
    private var currentStateDetail: CarCurrentDetailEntity? = null
    private var currentZqIdPage: String? = ""
    private var zqId_gl: String? = ""

    private var observers: MutableList<CarStateChangeObserver> = mutableListOf()

    companion object {
        private var instance: CarStatePool? = null
            get() {
                if (field == null) {
                    field = CarStatePool()
                }
                return field
            }

        fun get(): CarStatePool {
            return instance!!
        }
    }

    /**
     * 获取当前定位信息
     */
    fun getCarStateDetail(): CarCurrentDetailEntity? = currentStateDetail
    /**
     * 获取当前警情详情界面的 警情
     */
    fun getCurrentZqidPage(): String? = currentZqIdPage
    /**
     * 设置当前警情详情界面的 警情
     */
    fun setCurrentZqidPage(zqid:String) {
        this.currentZqIdPage= zqid
    }

    /**
     * 获车辆关联的 警情
     */
    fun getZqidGl(): String? = zqId_gl
    /**
     * 设置获车辆关联的 警情
     */
    fun setZqidGl(zqid:String) {
        this.zqId_gl= zqid
    }


    /**
     * 开始定位
     */
    fun start() {
        mDispatchEngine.submit {
//            //定时请求  车辆状态
            Observable.interval(120, TimeUnit.SECONDS)
                .observeOn(Schedulers.io())
                .subscribe {
                    getCarState(false)
            }
//            getCarState(false)
        }
    }

    /**
     * 开始分发消息
     */
    private fun startDispatch(entity: CarCurrentDetailEntity) {
        mDispatchEngine.submit {
            try {
                observers.forEach {
                    mHandler.post {
                        try {
                            it.onCarStateChange(entity)

                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

        }
    }

    /**
     *获取 车辆状态
     */
     fun getCarState(isSwicth :Boolean) {
        LoggerManager.d("获取车辆信息--start")

        if ( FastStackUtil.getInstance().current!= null && FastStackUtil.getInstance().current.javaClass.getSimpleName() == "com.dcjt.firehotcarpad.moudle.LoginActivity") {
            return
        }
        ApiRepository1.getInstance().getCarStateDetail( )
            .subscribe(object : FastObserver<CarCurrentDetailEntity>() {


                override fun _onError(errorRes: Int, errorCode: Int, e: Throwable) {
                    super._onError(errorRes, errorCode, e)
                    LoggerManager.e("获取车辆状态错误")
                }

                override fun _onNext(entity: CarCurrentDetailEntity) {
                    LoggerManager.d("获取车辆信息"+Gson().toJson(entity))
                    if (entity!= null) {
                        setZqidGl(entity!!.clxx!!.jqid!!)
                        if (currentStateDetail !=null){
                            if (currentStateDetail!!.clxx!!.clmc!! != entity!!.clxx!!.clmc
                                ||currentStateDetail!!.clxx!!.cllxdm!! != entity!!.clxx!!.cllxdm
                                ||currentStateDetail!!.clxx!!.clzzzt!! != entity!!.clxx!!.clzzzt
//                            ||if (StringUtils.isEmpty(currentStateDetail!!.zzbxx!!.deptId!!) ||StringUtils.isEmpty(entity!!.zzbxx!!.deptId!!)) true else currentStateDetail!!.zzbxx!!.deptId!! != entity!!.zzbxx!!.deptId
                            ){
                                startDispatch(entity)
                            } else if (isSwicth){
                                //强制分发
                                startDispatch(entity)
                            }

                        }else{
                            startDispatch(entity)
                        }
                        currentStateDetail = entity
                    }
                }

            })
    }


    fun registerCarStateObserver(observer: CarStateChangeObserver) {
        observers.add(observer)
    }


    fun unRegisterCarStateObserver(observer: CarStateChangeObserver) {
        observers.remove(observer)
    }


    interface CarStateChangeObserver {
        fun onCarStateChange(carStateDetail: CarCurrentDetailEntity)
    }


}